package com.example.shardingsphere.config.shard;

import org.apache.shardingsphere.sharding.api.config.ShardingRuleConfiguration;
import org.apache.shardingsphere.sharding.api.config.rule.ShardingTableRuleConfiguration;
import org.apache.shardingsphere.sharding.api.config.strategy.sharding.StandardShardingStrategyConfiguration;

public class ShardingRuleConfig {

    private static ShardingTableRuleConfiguration initShardingStrategy() {
        // 配置 t_order 表规则
        ShardingTableRuleConfiguration orderTableRuleConfig = new
                ShardingTableRuleConfiguration("t_order", "service_order_$->{0..2}.t_order_$->{2020..2021}_$->{1..12}");

        // 配置分库策略
        orderTableRuleConfig.setDatabaseShardingStrategy(
                // id 库分片的字段, shardingAlgorithmName :分库算法的名字，要与 分库算法配置的名字一致
                new StandardShardingStrategyConfiguration("id", "dbShardingAlgorithm"));

        // 配置分表策略
        orderTableRuleConfig.setTableShardingStrategy(
                // create_date 表分片的字段
                new StandardShardingStrategyConfiguration
                        ("create_date", "tableShardingAlgorithm"));

        return orderTableRuleConfig;
    }

    /**
     * 初始化 分库分表规则配置
     *
     * @return
     */
    public static ShardingRuleConfiguration initShardingRuleConfiguration() {
        // 初始化分片策略
        ShardingRuleConfiguration shardingRuleConfig = new ShardingRuleConfiguration();
        shardingRuleConfig.getTables().add(initShardingStrategy());

        // 分库算法配置 dbShardingAlgorithm :分库策略的名字一致
        shardingRuleConfig.getShardingAlgorithms().put("dbShardingAlgorithm",
                // MOD : 取模分片算法
                ShardDBModConfig.shardDBAlgorithmsProps());


        // 分表的算法配置  tableShardingAlgorithm :分表策略的名字一致
        shardingRuleConfig.getShardingAlgorithms().put("tableShardingAlgorithm",
                // INTERVAL: 时间范围分片算法
                ShardTableCustomCreateDateRuleConfig.shardTableAlgorithmsPros());

        return shardingRuleConfig;
    }
}
